<template>
  <div class="map-picker-container">
    <div ref="mapContainer" class="map-container" :class="{ 'fullscreen': isFullscreen }">
      <!-- 地图容器 -->
      <div ref="mapWrapper" class="map-wrapper" :style="{ height: height }"></div>

      <!-- 加载遮罩 -->
      <div v-if="loading" class="loading-overlay">
        <div class="loading-content">
          <div class="loading-spinner"></div>
          <div class="loading-text">地图加载中...</div>
        </div>
      </div>

      <!-- 加载失败提示 -->
      <div v-if="!loading && !map" class="error-overlay">
        <div class="error-content">
          <div class="error-icon">
            <i class="el-icon-warning"></i>
          </div>
          <div class="error-text">地图加载失败</div>
          <el-button type="primary" size="small" @click="retryInit">重新加载</el-button>
        </div>
      </div>

      <!-- 操作控制面板 -->
      <div class="map-controls">
        <el-button type="default" size="small" @click="toggleFullscreen"
          :icon="isFullscreen ? 'el-icon-minus' : 'el-icon-full-screen'" :title="isFullscreen ? '退出全屏' : '全屏显示'">
          {{ isFullscreen ? "退出全屏" : "全屏" }}
        </el-button>



        <el-button type="success" size="small" @click="confirmSelection" icon="el-icon-check"
          :disabled="!selectedPosition">
          确认选择
        </el-button>

        <el-button v-if="selectedPosition" type="danger" size="small" @click="clearSelection" icon="el-icon-delete"
          title="清除选择">
          清除
        </el-button>
      </div>

      <!-- 提示信息 -->
      <div class="picker-tips" v-if="!selectedPosition">
        <div class="tips-content">
          <span class="tip-text">
            <i class="el-icon-info"></i>
            点击地图选择位置
          </span>
        </div>
      </div>

      <!-- 选择成功提示 -->
      <div class="picker-tips success-tips" v-if="selectedPosition">
        <div class="tips-content">
          <span class="tip-text">
            <i class="el-icon-success"></i>
            位置已选择，点击标记查看详情
          </span>
        </div>
      </div>

      <!-- 选中位置信息 -->
      <div v-if="selectedPosition" class="position-info">
        <div class="info-header">
          <i class="el-icon-location-outline"></i>
          选中位置
        </div>
        <div class="info-content">
          <div class="coordinates">
            经度: {{ selectedPosition.longitude.toFixed(6) }}
          </div>
          <div class="coordinates">
            纬度: {{ selectedPosition.latitude.toFixed(6) }}
          </div>
          <div class="address" v-if="selectedPosition.address">
            地址: {{ selectedPosition.address }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { loadAMapScript } from "@/components/MapContainer/map-utils";

export default {
  name: "MapPicker",
  props: {
    // 地图中心坐标
    center: {
      type: Array,
      default: () => [116.397428, 39.90923], // 北京坐标
      validator: (value) => value.length === 2,
    },

    // 地图缩放级别
    zoom: {
      type: Number,
      default: 13,
      validator: (value) => value >= 3 && value <= 18,
    },

    // 地图容器高度
    height: {
      type: String,
      default: "400px",
    },

    // 初始选中位置
    value: {
      type: Object,
      default: null,
    },
  },

  data () {
    return {
      map: null, // 地图实例
      geocoder: null, // 地理编码实例
      marker: null, // 标记点
      infoWindow: null, // 信息窗口
      selectedPosition: null, // 选中的位置信息
      loading: true, // 是否正在加载
      isFullscreen: false, // 是否全屏状态
    };
  },

  async mounted () {
    try {
      await this.initMap();

      // 只有在地图初始化成功后才执行后续操作
      if (this.map) {
        this.initGeocoder();
        this.initMapEvents();

        // 如果有初始值，设置选中位置
        if (this.value) {
          this.setSelectedPosition(this.value);
        }
      }
    } catch (error) {
      console.error("MapPicker组件初始化失败:", error);
    } finally {
      this.loading = false;
      this.initFullscreenListener();
    }
  },

  watch: {
    value: {
      handler (newValue) {
        if (newValue) {
          this.setSelectedPosition(newValue);
        } else {
          this.clearSelection();
        }
      },
      deep: true,
      immediate: true,
    },

    center (newCenter) {
      if (this.map && newCenter) {
        this.map.setCenter(newCenter);
      }
    },

    zoom (newZoom) {
      if (this.map && newZoom) {
        this.map.setZoom(newZoom);
      }
    },
  },

  beforeDestroy () {
    this.removeFullscreenListener();
    if (this.infoWindow) {
      try {
        this.infoWindow.close();
      } catch (error) {
        console.warn('关闭信息窗口失败:', error);
      }
    }
    if (this.map) {
      try {
        this.map.destroy();
      } catch (error) {
        console.warn('销毁地图失败:', error);
      }
    }
  },

  methods: {
    // 初始化地图
    async initMap () {
      try {
        // 检查是否已经加载了AMap
        if (window.AMap) {
          this.createMap();
          return;
        }

        const AMap = await loadAMapScript();

        // 确保AMap已经正确加载
        if (!AMap) {
          throw new Error('AMap 加载失败');
        }

        this.createMap();

      } catch (error) {
        console.error("地图初始化失败:", error);
        this.loading = false;
        this.$message.error("地图加载失败，请检查网络连接或API密钥配置");
      }
    },

    // 创建地图实例
    createMap () {
      try {
        this.map = new window.AMap.Map(this.$refs.mapWrapper, {
          zoom: this.zoom,
          center: this.center,
          resizeEnable: true,
          dragEnable: true,
          zoomEnable: true,
          scrollWheel: true,
          doubleClickZoom: true,
          keyboardEnable: true,
          jogEnable: true,
          animateEnable: true,
        });

        // 添加地图控件（兼容不同版本的API）
        this.addMapControls();

        // 地图创建成功，设置loading为false
        this.loading = false;
        console.log("地图创建成功");

      } catch (error) {
        console.error("地图实例创建失败:", error);
        this.loading = false;
        this.$message.error("地图创建失败");
      }
    },

    // 添加地图控件（兼容不同版本的API）
    addMapControls () {
      try {
        // 尝试添加工具栏控件
        if (window.AMap.ToolBar) {
          if (typeof window.AMap.ToolBar === 'function') {
            this.map.addControl(new window.AMap.ToolBar({
              position: {
                top: '10px',
                right: '10px'
              }
            }))
          } else {
            this.map.addControl(window.AMap.ToolBar({
              position: {
                top: '10px',
                right: '10px'
              }
            }))
          }
        }
      } catch (error) {
        console.warn('添加工具栏控件失败:', error)
        this.loadMapPlugins()
      }

      try {
        // 尝试添加比例尺控件
        if (window.AMap.Scale) {
          if (typeof window.AMap.Scale === 'function') {
            this.map.addControl(new window.AMap.Scale({
              position: {
                bottom: '10px',
                left: '10px'
              }
            }))
          } else {
            this.map.addControl(window.AMap.Scale({
              position: {
                bottom: '10px',
                left: '10px'
              }
            }))
          }
        }
      } catch (error) {
        console.warn('添加比例尺控件失败:', error)
      }
    },

    // 加载地图插件
    loadMapPlugins () {
      if (!window.AMap || !window.AMap.plugin) {
        console.warn('高德地图API未完全加载，无法使用插件功能')
        return
      }

      window.AMap.plugin(['AMap.Scale', 'AMap.ToolBar'], () => {
        try {
          if (window.AMap.Scale) {
            const scale = new window.AMap.Scale({
              position: {
                bottom: '10px',
                left: '10px'
              }
            })
            this.map.addControl(scale)
          }

          if (window.AMap.ToolBar) {
            const toolBar = new window.AMap.ToolBar({
              position: {
                top: '10px',
                right: '10px'
              }
            })
            this.map.addControl(toolBar)
          }
        } catch (error) {
          console.warn('插件方式添加控件失败:', error)
        }
      })
    },

    // 初始化地理编码
    initGeocoder () {
      try {
        if (window.AMap && window.AMap.Geocoder) {
          if (typeof window.AMap.Geocoder === 'function') {
            this.geocoder = new window.AMap.Geocoder({
              city: "全国",
              radius: 1000,
            })
          } else {
            this.geocoder = window.AMap.Geocoder({
              city: "全国",
              radius: 1000,
            })
          }
        } else {
          // 如果Geocoder不可用，使用插件方式加载
          this.loadGeocoderPlugin()
        }
      } catch (error) {
        console.warn('初始化地理编码失败:', error)
        this.loadGeocoderPlugin()
      }
    },

    // 加载地理编码插件
    loadGeocoderPlugin () {
      if (!window.AMap || !window.AMap.plugin) {
        console.warn('高德地图API未完全加载，无法使用地理编码功能')
        return
      }

      window.AMap.plugin('AMap.Geocoder', () => {
        try {
          this.geocoder = new window.AMap.Geocoder({
            city: "全国",
            radius: 1000,
          })
        } catch (error) {
          console.warn('插件方式初始化地理编码失败:', error)
        }
      })
    },

    // 初始化地图事件
    initMapEvents () {
      if (this.map) {
        this.map.on('click', this.onMapClick);
      }
    },

    // 地图点击事件
    onMapClick (e) {
      const { lng, lat } = e.lnglat;
      this.setMarker(lng, lat);
      this.getAddressByLocation(lng, lat);

      // 显示选择成功的消息
      this.$message.success('位置已选择');
    },

    // 设置标记点
    setMarker (lng, lat) {
      // 检查地图是否已初始化
      if (!this.map) {
        console.warn('地图未初始化，无法设置标记');
        return;
      }

      // 移除之前的标记
      if (this.marker) {
        try {
          this.map.remove(this.marker);
        } catch (error) {
          console.warn('移除旧标记失败:', error);
        }
      }

      // 创建自定义标记图标 - 使用简单圆形以获得更精确的定位
      const markerContent = `
        <div class="custom-marker">
          <div class="marker-pin">
            <div class="marker-icon">
              <i class="el-icon-location"></i>
            </div>
          </div>
          <div class="marker-pulse"></div>
          <div class="marker-dot"></div>
        </div>
      `;

      // 创建新标记 - 精确定位让中心点对准点击位置
      try {
        this.marker = new window.AMap.Marker({
          position: [lng, lat],
          content: markerContent,
          offset: new window.AMap.Pixel(0, 0),
          anchor: 'center'
        });

        this.map.add(this.marker);
      } catch (error) {
        console.error('创建标记失败:', error);
        return;
      }

      // 添加点击动画效果
      this.$nextTick(() => {
        try {
          const markerElement = this.marker.getContent();
          if (markerElement && markerElement.classList && typeof markerElement.classList.add === 'function') {
            markerElement.classList.add('marker-animate');
            setTimeout(() => {
              if (markerElement && markerElement.classList && typeof markerElement.classList.remove === 'function') {
                markerElement.classList.remove('marker-animate');
              }
            }, 600);
          }
        } catch (error) {
          console.warn('添加标记动画效果失败:', error);
        }
      });

      // 添加标记点击事件
      try {
        this.marker.on('click', () => {
          this.showInfoWindow(lng, lat);
        });
      } catch (error) {
        console.warn('添加标记点击事件失败:', error);
      }
    },

    // 根据坐标获取地址
    getAddressByLocation (lng, lat) {
      if (!this.geocoder) return;

      this.geocoder.getAddress([lng, lat], (status, result) => {
        let address = '';
        let province = '';
        let city = '';
        let district = '';
        if (status === 'complete' && result.info === 'OK') {
          if (result.regeocode && result.regeocode.formattedAddress) {
            address = result.regeocode.formattedAddress;
            province = result.regeocode.addressComponent.province;
            city = result.regeocode.addressComponent.city;
            district = result.regeocode.addressComponent.district;

            // 处理市字段为空的情况：如果市为空，则使用省级单位地址填充
            if (!city || city.trim() === '') {
              // 检查是否有省级单位信息
              if (province && province.trim() !== '') {
                city = province; // 使用省级单位作为市级单位
                console.log(`市字段为空，使用省级单位填充: ${province}`);
              }
            }
          }
        }

        this.selectedPosition = {
          longitude: lng,
          latitude: lat,
          address: address,
          province: province,
          city: city,
          district: district,
        };

        // 添加调试日志
        console.log('逆地理编码结果:', {
          province: province,
          city: city,
          district: district,
          address: address
        });
      });
    },

    // 设置选中位置
    setSelectedPosition (position) {
      if (position && position.longitude && position.latitude && this.map) {
        this.selectedPosition = { ...position };
        this.setMarker(position.longitude, position.latitude);
        try {
          this.map.setCenter([position.longitude, position.latitude]);
        } catch (error) {
          console.warn('设置地图中心点失败:', error);
        }
      }
    },

    // 清除选择
    clearSelection () {
      this.selectedPosition = null;
      if (this.marker && this.map) {
        try {
          this.map.remove(this.marker);
        } catch (error) {
          console.warn('移除标记失败:', error);
        }
        this.marker = null;
      }
      // 关闭信息窗口
      if (this.infoWindow) {
        try {
          this.infoWindow.close();
        } catch (error) {
          console.warn('关闭信息窗口失败:', error);
        }
      }
    },

    // 显示信息窗口
    showInfoWindow (lng, lat) {
      if (!this.selectedPosition) return;

      const content = `
        <div class="info-window">
          <div class="info-title">
            <i class="el-icon-location-outline"></i>
            选中位置
          </div>
          <div class="info-content">
            <div class="coordinate-item">
              <span class="label">经度:</span>
              <span class="value">${lng.toFixed(6)}</span>
            </div>
            <div class="coordinate-item">
              <span class="label">纬度:</span>
              <span class="value">${lat.toFixed(6)}</span>
            </div>
            ${this.selectedPosition.address ? `
              <div class="address-item">
                <span class="label">地址:</span>
                <span class="value">${this.selectedPosition.address}</span>
              </div>
            ` : ''}
          </div>
        </div>
      `;

      // 创建信息窗口
      this.infoWindow = new window.AMap.InfoWindow({
        content: content,
        offset: new window.AMap.Pixel(0, -40),
        closeWhenClickMap: true
      });

      this.infoWindow.open(this.map, [lng, lat]);
    },



    // 确认选择
    confirmSelection () {
      if (this.selectedPosition) {
        this.$emit('confirm', this.selectedPosition);
      }
    },

    // 重试初始化
    async retryInit () {
      this.loading = true;
      this.map = null;

      try {
        await this.initMap();

        if (this.map) {
          this.initGeocoder();
          this.initMapEvents();

          if (this.value) {
            this.setSelectedPosition(this.value);
          }
        }
      } catch (error) {
        console.error("重试初始化失败:", error);
      } finally {
        this.loading = false;
      }
    },

    // 切换全屏
    toggleFullscreen () {
      this.isFullscreen = !this.isFullscreen;

      this.$nextTick(() => {
        if (this.map) {
          this.map.getViewport().style.height = this.height;
          this.map.getViewport().style.width = '100%';
          this.map.getContainer().style.height = this.height;
          this.map.getContainer().style.width = '100%';
          this.map.getSize();
          this.map.setFitView();
        }
      });
    },

    // 初始化全屏监听
    initFullscreenListener () {
      const events = ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'];
      events.forEach(event => {
        document.addEventListener(event, this.handleFullscreenChange);
      });
    },

    // 移除全屏监听
    removeFullscreenListener () {
      const events = ['fullscreenchange', 'webkitfullscreenchange', 'mozfullscreenchange', 'MSFullscreenChange'];
      events.forEach(event => {
        document.removeEventListener(event, this.handleFullscreenChange);
      });
    },

    // 处理全屏变化
    handleFullscreenChange () {
      const isFullscreen = !!(
        document.fullscreenElement ||
        document.webkitFullscreenElement ||
        document.mozFullScreenElement ||
        document.msFullscreenElement
      );

      if (!isFullscreen && this.isFullscreen) {
        this.isFullscreen = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.map-picker-container {
  position: relative;
  width: 100%;

  .map-container {
    position: relative;
    width: 100%;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    overflow: hidden;

    &.fullscreen {
      position: fixed;
      top: 0;
      left: 0;
      width: 100vw !important;
      height: 100vh !important;
      z-index: 9999;
      border: none;
      border-radius: 0;

      .map-wrapper {
        height: 100vh !important;
      }
    }
  }

  .map-wrapper {
    width: 100%;
    position: relative;
  }

  .loading-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.9);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;

    .loading-content {
      text-align: center;

      .loading-spinner {
        width: 40px;
        height: 40px;
        border: 4px solid #f3f3f3;
        border-top: 4px solid #409eff;
        border-radius: 50%;
        animation: spin 1s linear infinite;
        margin: 0 auto 10px;
      }

      .loading-text {
        color: #666;
        font-size: 14px;
      }
    }
  }

  .error-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(255, 255, 255, 0.95);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;

    .error-content {
      text-align: center;

      .error-icon {
        font-size: 48px;
        color: #f56c6c;
        margin-bottom: 16px;
      }

      .error-text {
        color: #666;
        font-size: 16px;
        margin-bottom: 16px;
      }
    }
  }

  .map-controls {
    position: absolute;
    top: 10px;
    left: 10px;
    z-index: 1000;
    display: flex;
    gap: 8px;

    .el-button {
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
  }

  .picker-tips {
    position: absolute;
    bottom: 60px;
    left: 50%;
    transform: translateX(-50%);
    z-index: 1000;

    .tips-content {
      background: rgba(0, 0, 0, 0.8);
      color: white;
      padding: 8px 12px;
      border-radius: 4px;
      font-size: 12px;
      white-space: nowrap;

      .tip-text {
        display: flex;
        align-items: center;
        gap: 4px;
      }
    }

    &.success-tips {
      .tips-content {
        background: rgba(103, 194, 58, 0.9);
        color: white;
      }
    }
  }

  .position-info {
    position: absolute;
    bottom: 10px;
    left: 10px;
    background: white;
    border: 1px solid #e4e7ed;
    border-radius: 4px;
    padding: 10px;
    max-width: 300px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    z-index: 1000;

    .info-header {
      display: flex;
      align-items: center;
      gap: 4px;
      font-weight: 500;
      color: #409eff;
      margin-bottom: 8px;
      font-size: 14px;
    }

    .info-content {
      .coordinates {
        font-size: 12px;
        color: #666;
        margin-bottom: 4px;
      }

      .address {
        font-size: 12px;
        color: #333;
        line-height: 1.4;
        word-break: break-all;
      }
    }
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
    opacity: 1;
  }

  100% {
    transform: scale(2);
    opacity: 0;
  }
}

@keyframes bounce {

  0%,
  20%,
  50%,
  80%,
  100% {
    transform: translateY(0);
  }

  40% {
    transform: translateY(-10px);
  }

  60% {
    transform: translateY(-5px);
  }
}

// 全屏时的样式调整
.fullscreen {
  .map-controls {
    top: 20px;
    left: 20px;
  }

  .picker-tips {
    bottom: 80px;
  }

  .position-info {
    bottom: 20px;
    left: 20px;
  }
}

// 自定义标记样式（全局样式，不使用scoped）
:global(.custom-marker) {
  position: relative;
  cursor: pointer;
  width: 40px;
  height: 40px;

  .marker-pin {
    position: absolute;
    top: 5px;
    left: 5px;
    width: 30px;
    height: 30px;
    background: #409eff;
    border: 3px solid #ffffff;
    border-radius: 50% 50% 50% 0;
    transform: rotate(-45deg);
    transform-origin: center;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.3);
    z-index: 2;
    transition: all 0.3s ease;

    .marker-icon {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%) rotate(45deg);
      color: white;
      font-size: 16px;
      font-weight: bold;
      transition: all 0.3s ease;
    }
  }

  .marker-pulse {
    position: absolute;
    top: 5px;
    left: 5px;
    width: 30px;
    height: 30px;
    background: #409eff;
    border-radius: 50%;
    opacity: 0.6;
    animation: pulse 2s infinite;
    z-index: 1;
  }

  .marker-dot {
    position: absolute;
    top: 50%;
    left: 50%;
    width: 2px;
    height: 2px;
    background: #ffffff;
    border: 1px solid #333;
    border-radius: 50%;
    transform: translate(-50%, -50%);
    z-index: 10;
    box-shadow: 0 0 3px rgba(0, 0, 0, 0.5);
  }

  &:hover {
    .marker-pin {
      background: #67c23a;
      transform: rotate(-45deg) scale(1.1);
      transform-origin: center;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4);
    }

    .marker-pulse {
      background: #67c23a;
      animation-duration: 1s;
    }
  }

  &.marker-animate {
    .marker-pin {
      animation: bounce 0.6s ease-in-out;
    }
  }
}

// 信息窗口样式
:global(.info-window) {
  padding: 12px;
  min-width: 200px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;

  .info-title {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 14px;
    font-weight: 600;
    color: #409eff;
    margin-bottom: 8px;
    border-bottom: 1px solid #e4e7ed;
    padding-bottom: 6px;
  }

  .info-content {

    .coordinate-item,
    .address-item {
      display: flex;
      margin-bottom: 4px;
      font-size: 12px;

      .label {
        color: #666;
        min-width: 40px;
        font-weight: 500;
      }

      .value {
        color: #333;
        flex: 1;
        word-break: break-all;
      }
    }

    .address-item {
      margin-top: 6px;
      padding-top: 6px;
      border-top: 1px solid #f0f0f0;

      .value {
        line-height: 1.4;
      }
    }
  }
}
</style>
